package com.kushe.dao;


import com.kushe.config.Config;
import com.kushe.entity.Comment;
import com.kushe.entity.Topics;
import com.kushe.util.core.DbUtils;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.QueryResult;
import org.nutz.dao.pager.Pager;
import org.springframework.data.redis.listener.Topic;

import java.util.List;

/**
 * Created by WSDevotion on 2015/5/2.
 */
public class CommentDao {
    public static Comment get(int id) {
        return DbUtils.getNutzDao().fetch(Comment.class, id);
    }


    public static Comment addComment(Comment comment) {
        Dao dao = DbUtils.getNutzDao();
        Topics topics = dao.fetch(Topics.class, comment.getTopic_id());
        if (topics != null) {
            dao.insert(comment);
            return comment;
        } else
            return null;
    }


    public static QueryResult getByTopics(int pageNumber, int topic_id) {
        Dao dao = DbUtils.getNutzDao();
        Pager pager = dao.createPager(pageNumber, Config.PAGE_SIZE);
        List<Comment> list = null;
        Topics topics = dao.fetch(Topics.class, topic_id);
        if(topics!=null) {
            list = dao.query(Comment.class, Cnd.where("topic_id", "=", topic_id), pager);
        }else{
            return null;
        }
        pager.setRecordCount(dao.count(Comment.class, Cnd.where("topic_id", "=", topic_id)));
        return new QueryResult(list, pager);
    }

    public static void deleteid(int id){
        Dao dao = DbUtils.getNutzDao();
        dao.delete(Comment.class, id);
    }

    public static void deleteTopics(int topic_id){
        Dao dao = DbUtils.getNutzDao();
        dao.clear(Comment.class, Cnd.where("topic_id", "=", topic_id));
    }

    public static List<Comment> getCommentByUser_id(int user_id){
        return DbUtils.getNutzDao().query(Comment.class, Cnd.where("user_id", "=", user_id));
    }


    public static void updateGroup(Topic topic){
        Dao dao = DbUtils.getNutzDao();
        dao.update(topic);
    }
}
